/**
 * Author zdc
 * 公共函数
 */
function getUrlParameter(property,url) {
    var LocString = url||String(window.location.href);
    var rs = new RegExp("(^|)" + property + "=([^\&]*)(\&|$)", "gi")
        .exec(LocString), tmp;
   
    if (tmp = rs) {
    	return tmp[2].replace(/\s/g,encodeURI(" "));
    }
    return "";
};


function getDic(callback){
	showLoading();
	$.ajax({
		type:'post',
		url:'./controlservice/DataMasterMappingAction/getDataMasterMappingInfo',
		data:{
		},
		dataType:'json',
		success:function(response){
			Global.selectSource=response;
			if(callback)callback();
			hideLoading();
		},
		error:function(response){
			hideLoading();
			console.log("获取全局字典表出错");
		}
	});
}
function getRegionRights(){
	var mms = "'"+Global.mmRights.join("','")+"'";
	$.ajax({
		type:'post',
		url:'./services/queryservice/region',
		data:{
			mms:mms
		},
		dataType:'json',
		success:function(response){
			Global.regionRights=response;
		},
		error:function(response){
			console.log("获取region出错");
		}
	});
}

function getMarketRights(){
	var mms = "'"+Global.mmRights.join("','")+"'";
	$.ajax({
		type:'post',
		url:'./services/queryservice/market',
		data:{
			mms:mms
		},
		dataType:'json',
		success:function(response){
			Global.marketRights=response;
		},
		error:function(response){
			console.log("获取market出错");
		}
	});
}

function getCityRights(){
	var mms = "'"+Global.mmRights.join("','")+"'";
	$.ajax({
		type:'post',
		url:'./services/queryservice/city',
		data:{
			mms:mms
		},
		dataType:'json',
		success:function(response){
			Global.cityRights=response;
		},
		error:function(response){
			console.log("获取city出错");
			hideLoading();
		}
	});
}

function getDicLabel(dic,code){
	dic=(Global.selectSource||{})[dic];
	if(dic){
		for(var item in dic){
			item=dic[item];
			if(item.Dict_Code==code){
				return item.Type_EnName;
			}
		}
	}
	return "";
}
var oldErrorLog=console.error;
console.error=function(e){
	if(e.stack&&e.stack.indexOf("Request canceled")>-1){
//		console.log("取消");
	}else{
		console.log(arguments);
	}
};

function getItems(domNode,flag){
    var clone = {};
    var jDoms = $("input[type='text'],select,textarea,td,span",domNode);
    for(var i= 0,length=jDoms.length;i<length;i++){
        var dom = jDoms[i];
        var issave = dom.attributes['issave'];
        if (issave && issave.value == "true"){
        	 var isComp2 = dom.attributes['isComp2'];
        	 var dbfield = dom.attributes['dbfield'].value;
        	 if (dbfield){
        		 var value = "";
            	 if (dom.tagName == "TD" || dom.tagName == "SPAN"){
            		 value = dom.innerHTML;
    			 }else{
    				 value = dom.value;
    				 if(dom.attributes['isfinance']){
    					 value = delCommafy(value);
    				 }
    			 }
            	 if (isComp2 && value !=""){
            		 value = (value/100).toFixed(3);
            	 }
                 clone[dbfield] = value;
        	 }
        	
        }
    }
    if (flag){//pp特殊不用flag属性
    	 clone["flag"] = "Active";
    }
    return clone;
};

//设置
function setItems(domNode,attributes,prefix){
	var doms = dojo.query("*[dbfield]",domNode);
	for(var dom in doms){
		dom = doms[dom];
		var data = dojo.attr(dom,"dbfield");
		if(data){
			if (dojo.attr(dom,"dataSource")){//下拉框选择
				selOption(dom,attributes[prefix + data]);
			}else{
				if (attributes[prefix + data]){
					var intValue = attributes[prefix + data];
					if (dojo.attr(dom,"isfinance")){
						intValue = parseFloat(intValue).toFixed(0); 
						intValue = setCommafy(intValue);
					}
					if (dojo.attr(dom,"isComp")){
						intValue = setComp(intValue);
					}
					if (dojo.attr(dom,"isComp2")){
						intValue = (intValue * 100).toFixed(1);
					}
					if (dom.tagName == "INPUT"){
						dom.value = intValue;
					}else{
						dom.innerHTML = intValue;
					}
					
				}
			}
		}
	}
}

function setCommafy(num){
	 num = parseFloat(num).toFixed(0); 
	 var re = /(-?\d+)(\d{3})/;
     while (re.test(num)) {
    	 num = num.replace(re, "$1,$2");
     }
     return num;
}
function delCommafy(num){
	 if((num+"").trim() == ""){
	    return "";
	 }
	 num = num.replace(/,/gi,'');
	 return num;
}

function setComp(value){
	var intValue = (parseFloat(value) * 100).toFixed(1) + "%";
	return intValue;
}


function  checkFieldsValid(domNode,scrolldom,scrolldom2){
    //检查require
    var jDoms = $("input[type='text'],select,textarea",domNode);
    for(var i= 0,length=jDoms.length;i<length;i++){
    	var dom = jDoms[i];
    	if(!checkFieldValid(dom,scrolldom,scrolldom2))return false;
    }
    return true;
}
function checkFieldValid(dom,scrolldom,scrolldom2){
   
	var issave = eval(dom.attributes['issave']);
	if (!issave){
		return true;
	}
	var tagName = dom.tagName.toLowerCase();
    var required = eval(dom.attributes['required']);
    if(required){
        var needTip = false;//标识是否需要提示
        if((tagName == "input" && $.trim(dom.value) == '') || (tagName == "select" && dom.value == "") || (tagName == "textarea" && $.trim(dom.value) == '')){
            needTip = true;
        }
        if(needTip){
        	scrollToDom(dom,scrolldom,scrolldom2);
        	if (tagName == "textarea"){
        		setDompopover(dom,"该字段为必填字段","top");
        	}else{
        		setDompopover(dom,"该字段为必填字段");
        	}
            return false;
        }
    }
    
    var regatt = dom.attributes['reg'];
    if (regatt && dom.attributes['reg'].value){
    	var reg = new RegExp(ioc.reg[dom.attributes['reg'].value].value);
    	if (dom.value == ""){
    	    return true;
    	}
    	if (!reg.test(dom.attributes['isfinance']?delCommafy(dom.value):dom.value)){
    		scrollToDom(dom,scrolldom,scrolldom2);
    		var tip = ioc.reg[dom.attributes['reg'].value].tip;
    		
    		setDompopover(dom,tip);
            return false;
    	}
    }
    return true;
}

function setDompopover(dom,tip,place){
	if (!place){
		place = "right";
	}
	 var args = {
             placement:place,
             content:tip,
             container: 'body'
      };
	 $(dom).popover(args).popover("show");
     setTimeout(function(){
         $("div.popover").remove();
         $(dom).popover('destroy');
     },2000);
}

//验证单个节点
function checkDom(dom,place){
    var regatt = dom.attributes['reg'];
	 if (regatt && dom.attributes['reg'].value){
	    	var reg = new RegExp(ioc.reg[dom.attributes['reg'].value].value);
	    	if (dom.value == ""){
	    	    return true;
	    	}
	    	if (!reg.test(dom.attributes['isfinance']?delCommafy(dom.value):dom.value)){
	    		var tip = ioc.reg[dom.attributes['reg'].value].tip;
	    		setDompopover(dom,tip,place);
	            return false;
	    	}
	}
	return true;
}

//自动滚动到dom节点 scroldom含有滚动条的dom,dom需要定位的dom
function scrollToDom(dom,scrolldom,scrolldom2) {
	if (scrolldom){
		 var y1 = dojo.coords(dom).y;
		  var y2 = dojo.coords(scrolldom).y;
		  var value = y1 - y2;

		  var topvalue = scrolldom.scrollTop;
		  scrolldom.scrollTop = value + topvalue;
		  window.scrollTo(0,value + topvalue);
	}
	if (scrolldom2){
		  var y1 = dojo.coords(dom).y;
		  var y2 = dojo.coords(scrolldom2).y;
		  var value = y1 - y2;

		  var topvalue = scrolldom2.scrollTop;
		  scrolldom2.scrollTop = value + topvalue;
	} 
}


function sortByFields(fields,path,a,b){
	var getValueByPath=function(item,path){
		if(path){
			var arr=path.split(",");
			for(var i=0;i<arr.length;i++){
				item=item[arr[i]];
				if(!item){
					return {};
				}
			}
		}else{
			return item;
		}
		return item;
	};
	for(var i=0;i<fields.length;i++){
		var field=fields[i].split(" ");
		var isAsc=field.length==1||field[1]!="desc";
		var av=getValueByPath(a,path)[field[0]],bv=getValueByPath(b,path)[field[0]];
		if(av!=null&&bv==null){
			return -1;
		}else if(av==null&&bv!=null){
			return 1;
		}else if(av!=null&&bv!=null&&av>bv){
			return isAsc?1:-1;
		}else if(av!=null&&bv!=null&&av<bv){
			return isAsc?-1:1;
		}
	}
	return 0;
}

function setSelectOptions(dom){
	var source=Global.selectSource;
	var opStr=Global.language == "zh-cn"?"--请选择--":"--Select--";
	if(source){
		var selects=dojo.query("select[dataSource]",dom);
		for(var select in selects){
			select=selects[select];
			var data=source[dojo.attr(select,"dataSource")];
			if(data&&select.options.length==0){
				select.add(dojo.toDom("<option value=''>"+ opStr +"</option>"));
				data.sort(function(a,b){ return a.Type_EnName.charCodeAt(0)-b.Type_EnName.charCodeAt(0); });
				for(var item in data){
					item=data[item];
					select.add(dojo.toDom("<option value='"+item.Dict_Code+"'>"+item.Type_EnName+"</option>"));
				}
			}
		}
	}
	dojo.query(".cur-select",dom).forEach(function(item){ item.innerHTML = Global.language == "zh-cn"?"--请选择--":"--Select--";});
}

function getValueFromSelSource(datasource,value){
	var source=Global.selectSource;
	if (value && source){
		var data = source[datasource];
		if(data){
			for(var item in data){
				item=data[item];
				if(value == item.Dict_Code){
					return item.Type_EnName;
				}
			}
		}
	}
	return value;
}

function selOption(dom,diccode){
	var options = dom.options;
	for (var i = 0; i < options.length; i++){
		if (options[i].value != "" && options[i].value == diccode){
			options[i].selected  = "selected";
			var outSpan = $(options[i]).parent().parent().find("span")[0];
			if(outSpan)outSpan.innerHTML= options[i].innerHTML;
			break;
		}
	}
}
function showLoading(){
//	 $('body').showLoading();
	var message = Global.language == "zh-cn"?"正在加载...":"Loading...";
	var bc ='<div class="modal-backdrop  in"></div>';
	var load = '<div class="blockui modal" style="display: block;"><div class="modal-dialog"><img class="ball" src="images/ball.png" /><div class="msg">'+message+'</div></div></div>';
	$('body').append(bc);
	$('body').append(load);
}
function hideLoading(){
//	$('body').hideLoading();
	$('body > .modal-backdrop').remove();
	$('body > .blockui').remove();
}
function showTxtLoading(){
	$('body').showLoading();
}
function hideTxtLoading(){
	$('body').hideLoading();
}
function log(type,name,description){
	var operation = "";
	var operationType ="";
	var operationDescription ="";
	operationType = type;
	if (description){
		operationDescription = name;
		operation= description;
	}else{
		var result = getLogOperation(name);
		operation = result.operator;
		operationDescription = result.operatordes;
	}
	var data={
			operation:operation,
			operationType:operationType,
			operationDescription:operationDescription
		};
	$.ajax({
		type:'post',
		url:'./controlservice/gis_Log/add',
		data:{
			model:JSON.stringify(data)
		},
		dataType:'json',
		success:function(response){
			console.log("log:"+name);
		},
		error:function(response){
			console.log("日志写入出错");
		}
    });
}

function getLogOperation(operation){
	//debugger;
	 var result = {};
	 for(var i= 0;i<ioc.ENandCN.length;i++){
	        var dom = ioc.ENandCN[i];
	        if(dom.en == operation || dom.cn == operation){
	        	result["operatordes"] = dom.operation;
	        	if (dom.operation2){
	        		result["operator"] = dom.operation2;
	        	}else{
	        		result["operator"] = dom.en;
	        	}
	        	break;
	        }
	 }
	 return result;
}


function setFormDisabled(domNode){
	var jDoms = $("input[type='text'],select,textarea",domNode);
    for(var i= 0,length=jDoms.length;i<length;i++){
        var dom = jDoms[i];
        dom.disabled = "disabled";
    }
}


/**
 * 显示自定义的提示消息
 * @param msg 提示消息
 * @param bError 是否为错误提示
 */
function showMessage(msg, time, dom, bError) {
	
	require(["widgets/tooltip/Tooltip"],function(Tooltip){
		var speed = 8;//8字符/秒
	    time = Math.ceil(msg.length / speed) * 1000;
	    bError = (bError != undefined) ? bError : true;
	    new Tooltip({"contentStr":msg, time:time, relativeParent:dojo.body(), bError:bError});
	});
    
}
function confirmInfo(info,callback,title){
	require(["widgets/formWindow/confirmInfoWidget/ConfirmWidget"],function(ConfirmWidget){
		var win=new ConfirmWidget({
			text:info,
			title:title||"",callback:callback
		});
		win.startup();
		win.placeAt(dojo.body());
	});
}


/**
 * 根据Input元素，为前面的span元素追加*
 * @param curInput  input 元素id 
 */
function addStarStyle(curInput) {
    curInput = '#' + curInput;
    var curSpan = $(curInput).prev();
    var starStyle = '<span style="color: #f00;width: 3px;">*</span>';
    curSpan.append(starStyle); 
    /*if(curInput && $(curInput).prev() && $(curInput).prev()[0].nodeName =="SPAN" ){
        var curSpan = $(curInput).prev();
        var starStyle = '<span style="color: #f00;width: 3px;">*</span>';
        curSpan.append(starStyle); 
    }else {
        throw new Error("对象为空，或者对象前一个对象不是span元素");
    }*/
}

/**
 * 根据Input元素，为前面的span元素除去*
 * @param curInput  input 元素id 
 */
function addStarStyle(curInput) {
    curInput = '#' + curInput;
    if(curInput && $(curInput).prev() && $(curInput).prev()[0].nodeName =="SPAN" ){
        var curSpan = $(curInput).prev();
        var starStyle = '<span style="color: #f00;width: 3px;">*</span>';
        if(curSpan[0].innerHTML.indexOf("*") > 0){
            var cnt = curSpan[0].textContent;
            curSpan[0].innerHTML = cnt.substring(0,cnt.indexOf('*'));
        }
    }else {
        throw new Error("对象为空，或者对象前一个对象不是span元素");
    }
       
}

function slideCtrl(){
    $(".panel-wm-b").find(".panel-btn-close").click(function () {
        var $this = $(this);
        var $parent = $this.parent().parent();
        if ($parent.hasClass("panel-is-close")) {
            $parent.find(".panel-body").slideDown(200, function () {
                $parent.removeClass("panel-is-close");
            });
        } else {
            $parent.find(".panel-body").slideUp(200, function () {
                $parent.addClass("panel-is-close");
            });
        }
    });
}

function previewPDF(path){
	if (Global.device == "pc"){
		var portalUrl = getPortalUrl();
		window.parent.postMessage({

	        eventType:"addTab",

	        url:MGISURL + "/pdfShow.html?path=" + path,

	        title:"PreView"

	    },portalUrl);
	}else{
		window.open(MGISURL + path);
	}

}

function previewPic(path){
	var portalUrl = getPortalUrl();
	window.parent.postMessage({

        eventType:"addTab",

        url:MGISURL + "/picShow.html?path=" + path,

        title:"PreView"

    },portalUrl);
}

function setEn(domNode){
	if (Global.language != "zh-cn"){//英文
		var enlist = lang.en;
		var classname = "";
		var value = "";
		for (var i = 0; i < enlist.length; i++){
			classname = enlist[i].classname;
			var doms = null;
			if (domNode){
			     doms = dojo.query("."+classname+"",domNode);//DOM结点
			}else{
				 doms = dojo.query("."+classname+"");//DOM结点
			}
			
			if (doms){
				for (var j = 0; j < doms.length; j++){
					var dom = doms[j];
					value = enlist[i].en;  
					if (dom.children.length > 0){
						if (enlist[i].cn){
							var inner = dom.innerHTML;
							var reg=new RegExp(enlist[i].cn,"g"); //创建正则RegExp对象   
							var newstr=inner.replace(reg,value); 
							dom.innerHTML  = newstr;
						}else{
							dom.innerHTML = value + "<span class='text-red text-big'>*</span>";
						}
					}else{
						dom.innerHTML  = value;
					}
					
					if (dom.tagName == "LABEL"){
						dom.title = value;
					}
				}
			}
		}
   }
}

function setSingleEn(domclass,domNode){
	if (Global.language != "zh-cn"){//英文
		var enlist = lang.en;
		var classname = "";
		var value = "";
		for (var i = 0; i < enlist.length; i++){
			classname = enlist[i].classname;
			if (classname == domclass){
				var doms = dojo.query("."+classname+"",domNode);//DOM结点
				if (doms){
					for (var j = 0; j < doms.length; j++){
						var dom = doms[j];
						value = enlist[i].en;  
						dom.innerHTML = value;
						if (dom.tagName == "LABEL"){
							dom.title = value;
						}
					}
				}
				break;
			}
		}
   }
}

//获得Portal地址
function getPortalUrl(){
	if (Global.isMdp && Global.isMdp == "yes"){
		if (window.location.href.indexOf('02')>0){
			return PORTALURL202;
		}else{
			return PORTALURL2;
		}
		
	}else{
		if (window.location.href.indexOf('02')>0){
			return PORTALURL02;
		}else{
			return PORTALURL;
		}
	}
}

/**
 * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
 * 即谷歌、高德 转 百度
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function gaodeToBaidu(lng, lat) {
	var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
    var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
    var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
    var bd_lng = z * Math.cos(theta) + 0.0065;
    var bd_lat = z * Math.sin(theta) + 0.006;
    return [bd_lng, bd_lat];
}
function baiduToGaode(bd_lon, bd_lat) {
	var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    var x = bd_lon - 0.0065;
    var y = bd_lat - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    var gg_lng = z * Math.cos(theta);
    var gg_lat = z * Math.sin(theta);
    return [gg_lng, gg_lat]
}

//百分比四舍五入后归一
function evenRound(arr) {
	var decimal = -~arr.map(function( a ){ return a % 1; })
    .reduce(function( a,b ){ return a + b; }); // Ceil of total sum of decimals
	for ( var i = 0; i < decimal; ++i ) {
		arr[ i ] = ++arr[ i ]; // compensate error by adding 1 the the first n items
  	}
	return arr.map(function( a ){ return ~~a; }); // floor all other numbers
}
//因iphone单选框风格异常做的调整
function resetPhoneRadioBtn(node){
	if(Global.device == 'phone'){
		var domsY,domsN ;
		if(node){
			domsY = dojo.query(".en-yes",node);
			domsN = dojo.query(".en-no",node);
		}else{
			domsY = dojo.query(".en-yes");
			domsN = dojo.query(".en-no");
		}
		if ((domsY&&domsN)&&domsY.length==domsN.length){
			for (var i = 0; i < domsY.length; i++){
				var tmpYtxt = $(domsY[i]).text();
				var tmpNtxt = $(domsN[i]).text();
				domsY[i].innerHTML = dojo.query("input",domsY[i])[0].outerHTML + tmpNtxt;
				domsN[i].innerHTML = dojo.query("input",domsN[i])[0].outerHTML + tmpYtxt;
			}
		}
	}
}
//esri.config.defaults.io.errorHandler=function(){console.log(arguments)}